package net.result;

import com.opensymphony.xwork2.ActionInvocation;
import net.base.ToolsAction;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.StrutsRequestWrapper;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 11-9-17
 * Time: 下午3:29
 * To change this template use File | Settings | File Templates.
 */
public class JsonMutiHTMLResult extends BaseResult {
    private static final Log log = LogFactory.getLog(JsonHTMLResult.class);
    private String location;
    private String errorPage = "/commons/common/error.jsp";
    protected boolean isAjax = true;


    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getErrorPage() {
        return errorPage;
    }

    public void setErrorPage(String errorPage) {
        this.errorPage = errorPage;
    }

    public JsonMutiHTMLResult() {
        // TODO Auto-generated constructor stub
        super();
    }

    public JsonMutiHTMLResult(String location) {
        // TODO Auto-generated constructor stub
        super(location);
    }


    public void execute(ActionInvocation invocation) throws Exception {
        // TODO Auto-generated method stub
        long startTime = System.currentTimeMillis();
        ServletContext sc = ServletActionContext.getServletContext();
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        System.out.println("charset:" + request.getCharacterEncoding());
        response.setCharacterEncoding(request.getCharacterEncoding());
        response.setContentType("application/json;charset=" + request.getCharacterEncoding());


        StrutsRequestWrapper requestWrapper = new StrutsRequestWrapper(request);


        PrintWriter output = response.getWriter();
        ToolsAction baseAction = (ToolsAction) invocation.getAction();
        try {
            //	request.setAttribute("model", baseAction.getModel());


            String viewName = request.getParameter("viewName") == null ? this.location : request.getParameter("viewName");


            List resultList = new ArrayList();
            String[] viewNames = viewName.split(";");
            for (int i = 0; i < viewNames.length; i++) {
                String vName = viewNames[i];
                RequestDispatcher dispatcher = request.getRequestDispatcher(vName);
                ResponseWrapper responseWrapper = new ResponseWrapper(response);
                dispatcher.include(requestWrapper, responseWrapper);

                String content = responseWrapper.getContent();
                resultList.add(content.trim());
                responseWrapper.finalize();
            }


            JSONObject js = new JSONObject();
            js.put("code", new Integer(baseAction.getCode()));
            js.put("msg", baseAction.getMsg());
            js.put("expMsg", baseAction.getExpMsg());
            js.put("data", resultList);
            String resultContent = js.toString();
            log.info(resultContent);
            output.write(resultContent);
            output.flush();
        } catch (Exception ex) {
            HashMap hashMap = new HashMap();
            hashMap.put("code", "-1");
            hashMap.put("type", "err");
            hashMap.put("msg", "发生错误");
            hashMap.put("mx", ex.getMessage());


            JSONObject js = new JSONObject();
            js.put("msg", hashMap);
            output.write(js.toString());
        } finally {
            if (output != null) output.close();
        }
        log.info("use time " + (System.currentTimeMillis() - startTime) + " ms");
    }

    protected void doExecute(String location, ActionInvocation invocation) throws Exception {
        // TODO Auto-generated method stub
        this.location = location;
        this.execute(invocation);
    }
}
